import { Request, Response } from 'express';
import { asyncHandler, ApiError } from '../middlewares/errorHandler';
import prisma from '../config/database';

// 获取讨论列表
export const getDiscussions = asyncHandler(async (req: Request, res: Response) => {
  const { page = 1, limit = 20 } = req.query;

  const skip = (Number(page) - 1) * Number(limit);

  const [discussions, total] = await Promise.all([
    prisma.discussion.findMany({
      skip,
      take: Number(limit),
      include: {
        user: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
        _count: {
          select: {
            replies: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    }),
    prisma.discussion.count(),
  ]);

  res.json({
    code: 200,
    message: 'Success',
    data: {
      discussions,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total,
        totalPages: Math.ceil(total / Number(limit)),
      },
    },
  });
});

// 获取讨论详情
export const getDiscussionById = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;

  const discussion = await prisma.discussion.findUnique({
    where: { id },
    include: {
      user: {
        select: {
          id: true,
          username: true,
          avatar: true,
        },
      },
      replies: {
        include: {
          children: true,
        },
        orderBy: {
          createdAt: 'asc',
        },
      },
    },
  });

  if (!discussion) {
    throw new ApiError(404, 'Discussion not found');
  }

  // 增加浏览量
  await prisma.discussion.update({
    where: { id },
    data: {
      views: {
        increment: 1,
      },
    },
  });

  res.json({
    code: 200,
    message: 'Success',
    data: discussion,
  });
});

// 创建讨论
export const createDiscussion = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;
  const { title, content } = req.body;

  const discussion = await prisma.discussion.create({
    data: {
      userId,
      title,
      content,
    },
  });

  res.status(201).json({
    code: 201,
    message: 'Discussion created successfully',
    data: discussion,
  });
});

// 创建回复
export const createReply = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;
  const { id: discussionId } = req.params;
  const { content, parentId } = req.body;

  const reply = await prisma.reply.create({
    data: {
      userId,
      discussionId,
      content,
      parentId,
    },
  });

  res.status(201).json({
    code: 201,
    message: 'Reply created successfully',
    data: reply,
  });
});
